package com.htfyun.eink.pw.draw.pen.epd.charcoal;

public class CompositeMaskBmpHelper {

    private static final float RADIAN = 1.5708f;

    public static final float VAL_COS = (float) Math.cos(RADIAN);
    public static final float VAL_SIN = (float) Math.sin(RADIAN);

    public static void init(BitmapData bitmapData) {

        for (int i = 0; i < bitmapData.width; i++) {
            for (int j = 0; j < bitmapData.height; j++) {
                bitmapData.data[i][j] = 0xFFFFFFFF;
            }
        }

        final float halfRow = bitmapData.width * 0.5f;
        final float halfColumn = bitmapData.height * 0.5f;

        for (int row = 0; row < bitmapData.width; row++) {
            float rowDiff = row - halfRow;
            for (int column = 0; column < bitmapData.height; column++) {

                float columnDiff = column - halfColumn;

                float cos = columnDiff * VAL_COS - rowDiff * VAL_SIN;
                float sin = columnDiff * VAL_SIN + rowDiff * VAL_COS;

                int cp = compute(bitmapData.width, cos, sin);

                int data = bitmapData.data[row][column];
                int result = MathUtils.uint8_multiple((data >> 0x18), (~cp));

                bitmapData.data[row][column] = data & 0xFFFFFF | (result << 0x18);

            }
        }

    }

    private static int compute(int row, float cos, float sin) {

        float high = 2.0f / row;
        float low = 2.0f / (row * 0.5f);

        float x = high * cos;
        float y = high * Math.abs(sin);

        float hypotf1 = (float) Math.hypot(x, y);
        if (hypotf1 > 1.0F) {
            return 0xFF;
        }

        x = low * cos;
        y = low * Math.abs(sin);
        float hypotf2 = (float) Math.hypot(x, y);
        if (hypotf2 >= 1.0F) {
            return (int) (((hypotf1 * 0xFF) * (hypotf2 - 1.0f)) / (hypotf2 - hypotf1));
        }

        return 0;

    }
}
